/**
 * This file is where you define your application routes and controllers.
 *
 * Start by including the middleware you want to run for every request;
 * you can attach middleware to the pre('routes') and pre('render') events.
 *
 * For simplicity, the default setup for route controllers is for each to be
 * in its own file, and we import all the files in the /routes/views directory.
 *
 * Each of these files is a route controller, and is responsible for all the
 * processing that needs to happen for the route (e.g. loading data, handling
 * form submissions, rendering the view template, etc).
 *
 * Bind each route pattern your application should respond to in the function
 * that is exported from this module, following the examples below.
 *
 * See the Express application routing documentation for more information:
 * http://expressjs.com/api.html#app.VERB
 */

var keystone = require('keystone');
var useragent = require('express-useragent');

var User = keystone.list("User");
var importRoutes = keystone.importer(__dirname);
var bodyParser = require("body-parser");
var passport = require('passport')
var passport_config = require('./passport_config');

require("body-parser-xml")(bodyParser);
var middleware = require('./middleware');

passport_config.init("local", "", 'local_user');

keystone.pre("routes", passport.initialize());
keystone.pre("routes", passport.session());

//Configure Passport
passport.serializeUser(function (user, cb) {
	cb(null, user._id);
});

passport.deserializeUser(function (_id, cb) {
	User.model.findById(_id, function (err, user) {
		cb(err, user);
	})
});

// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('routes', useragent.express());
keystone.pre('render', middleware.flashMessages);

// Import Route Controllers
var routes = {
	views: importRoutes('./views'),
	next: importRoutes('./next'),

};


// Setup Route Bindings
exports = module.exports = function (app) {
	// Views
	app.get('/', routes.next.index);
	app.get('/index', routes.next.index);
	app.get('/a/index', routes.next.index);

	app.get('/v/', routes.views.index);
	app.get('/v/blog/:category?', routes.views.blog);
	app.get('/v/blog/post/:post', routes.views.post);
	app.get('/v/gallery', routes.views.gallery);
	app.all('/v/contact', routes.views.contact);

	app.post('/local/local_user', function (req, res, next) {

		passport.authenticate('local', {
			callbackURL: "https://" + req.hostname + "/local/local_user" +
				"?callback_url=" + req.body.callback_url
		}, function (err, user, info) {
			// console.log(user)
			if (err) { return next(err); }
			if (!user) {
				return res.json({ err: 1, info: info });
			}

			req.logIn(user, function (err) {
				if (err) { return next(err); }

				return res.json({
					err: 0,
					info: req.body.callback_url
				});
			});
		})(req, res, next);
	});

	app.get('/logout', function (req, res) {
		req.logout();
		if (req.query.callback_url) {
			return res.redirect(req.query.callback_url);
		}
		res.redirect('/');
	});

	app.use(bodyParser.xml({
		limit: "2MB",
		xmlParseOptions: {
			normalize: true,
			normalizeTags: true,
			explicitArray: false
		},
		verify: function (req, res, buf, encoding) {
			if (buf && buf.length) {
				req.rawBody = buf.toString(encoding || "utf8");
			}
		}
	}));
	app.use(bodyParser.json());


	// 登录
	app.get('/login', routes.next.login);
	app.get('/a/login', routes.next.login);
	// 获取用户列表
	app.get('/user_list', routes.next.get_message.user_list);
	// 删除用户
	app.post('/user_remove', routes.next.dispose_message.user_remove);
	// 编辑用户
	app.post('/submit_user_message', routes.next.dispose_message.submit_user_message);


	app.get("/_next*", (req, res) => keystone.next_handle(req, res));
	app.all("/*", (req, res) => keystone.next_handle(req, res));

	//app.get("/_webpack*", (req, res) => keystone.next_handle(req, res));
	// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
	// app.get('/protected', middleware.requireUser, routes.views.protected);
};

